package applePay

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"net/http"

	"github.com/Peakchen/xgameCommon/akLog"
)

func postVerifyReceipt(w http.ResponseWriter, r *http.Request, url string) {
	receiptData := base64.StdEncoding.EncodeToString([]byte(r.FormValue("ReceiptData")))
	request := &AppPayRequestBody{
		ReceiptData: receiptData,
		Password:    r.FormValue("Password"),
	}
	jsonReq, err := json.Marshal(request)
	if err != nil {
		w.Write([]byte(REQUST_DATA_MARSHAL_FAIL))
		return
	}
	resp, err := http.Post(url, ContentType, bytes.NewBuffer(jsonReq))
	if err != nil {
		w.Write([]byte(POST_DATA_FAIL))
		return
	}
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		w.Write([]byte(READ_RESPONSE_FAIL))
		return
	}
	var result = &AppPayResponseBody{}
	err = json.Unmarshal(respBody, result)
	if err != nil {
		w.Write([]byte(UNMARSHAL_RESPONSE_FAIL))
		return
	}
	akLog.FmtPrintln("app Pay content: ", *result)
	if result.Status >= AccessErrors_Min && result.Status <= AccessErrors_Max {
		w.Write([]byte(ACCESS_ERRORS))
		return
	}
	w.Write([]byte(RespBodyStatus[result.Status]))
}

//POST "https://buy.itunes.apple.com/verifyReceipt"
func AppPayCommonVerifyReceipt(w http.ResponseWriter, r *http.Request) {
	postVerifyReceipt(w, r, CommonUrl)
}

//POST "https://sandbox.itunes.apple.com/verifyReceipt"
func AppPaySandboxVerifyReceipt(w http.ResponseWriter, r *http.Request) {
	postVerifyReceipt(w, r, SandboxUrl)
}
